<template>
  <div class="content">
    <div class="breadcrumb" :gutter="24">

      <el-form ref="form" :model="formData" label-width="120px" size="small">
        <el-row :gutter="24">
          <el-col :xs="9" :sm="6" :md="5" :lg="5" :xl="4">
            <el-form-item :label="$t('system.menu_name')">
              <el-input v-model="formData.keyWord" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="2" :sm="2" :md="2" :lg="2" :xl="2">
            <el-form-item label-width="0px">
              <el-button type="primary" size="small" @click="handleSearch()">{{ $t("common.query") }}</el-button>
            </el-form-item>
          </el-col>
          <el-col :xs="13" :sm="16" :md="17" :lg="17" :xl="17">
            <div class="btngroup">
              <el-button type="primary" size="small" @click="handleAdd()">{{ $t("common.add") }}</el-button>
              <el-button type="primary" size="small" @click="handleEdit()">{{ $t("common.edit") }}</el-button>
              <el-button type="primary" size="small" @click="handleDel()">{{ $t("common.remove") }}</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>

    </div>

    <div class="tableAuto" style="clear:both">
      <el-table :data="tableData" style="width:100%" :height="height" @row-click="rowClick" border stripe
        :header-cell-style="{background:'#EAEBEC'}" v-loading="tableLoading" ref="refTable" highlight-current-row
        :row-class-name="getRowClass">
        <!-- <el-table-column label="" width="0" align="center">
                    <template slot-scope="scope">
                        <div :accesskey="scope.row.fid">
                            <el-radio :label="scope.row.fid" v-model="radioId">&nbsp;</el-radio>
                        </div>
                    </template>
                </el-table-column> -->
        <el-table-column type="expand">
          <template slot-scope="props">
            <div style="padding-left:120px">
              <el-table :data="props.row.children" style="width:100%" @row-click="rowClickChild" border stripe
                :header-cell-style="{background:'rgb(234, 235, 236)'}" ref="refTable1" highlight-current-row>
                <template slot-scope="props">
                  <!-- <el-table-column width="170" show-overflow-tooltip label=""></el-table-column> -->

                  <!-- <el-table-column label="" width="50" align="center">
                                    <template slot-scope="scope">
                                        <div :accesskey="scope.row.fid">
                                            <el-radio :label="scope.row.fid" v-model="childRadioId">&nbsp;</el-radio>
                                        </div>
                                    </template>
                                </el-table-column> -->
                  <el-table-column type="index" width="50" show-overflow-tooltip :label="$t('common.number')"></el-table-column>
                  <el-table-column prop="menuName" width="150" show-overflow-tooltip :label="$t('system.menu_name')"></el-table-column>
                  <el-table-column prop="orderNum" width="100" show-overflow-tooltip :label="$t('system.display_order')"></el-table-column>
                  <el-table-column prop="fLastModifyTime" width="150" show-overflow-tooltip
                    :label="$t('common.create_time')"></el-table-column>
                  <el-table-column prop="url" show-overflow-tooltip :label="$t('system.routing_address')"></el-table-column>
                </template>
              </el-table>
            </div>

          </template>

        </el-table-column>
        <el-table-column type="index" width="80" :label="$t('common.number')" align="center" sortable></el-table-column>
        <el-table-column prop="menuName" width="150" show-overflow-tooltip :label="$t('system.menu_name')"></el-table-column>
        <el-table-column prop="orderNum" width="100" show-overflow-tooltip :label="$t('system.display_order')"></el-table-column>
        <el-table-column prop="orderNum" width="100" show-overflow-tooltip :label="$t('system.list_type')">
          <template slot-scope="scope">
            <!-- <span>{{ scope.row.children.length ? '目录' : '菜单' }}</span> -->
            <!-- {{getMenuType(scope.row)}} -->
            {{scope.row.menuType == 'M' ? '目录' : '菜单'}}
          </template>
        </el-table-column>
        <el-table-column prop="fLastModifyTime" width="150" show-overflow-tooltip :label="$t('common.create_time')"></el-table-column>
        <el-table-column prop="url" show-overflow-tooltip :label="$t('system.routing_address')">
          <template slot-scope="scope">
            <span v-if="scope.row.children.length == 0">{{ scope.row.url }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog v-dialogDrag :title="title" :visible.sync="isShowAdd" :close-on-click-modal="false" width="35%" :before-close="handleClose">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="70px" size="small" :hide-required-asterisk="true">
        <el-row :gutter="24">
          <el-col :xs="24">
            <el-form-item :label="$t('system.menu_type')" prop="menuType" class="spread">
              <el-select v-model="ruleForm.menuType" filterable placeholder="请选择" @change="changeMenuType">
                <el-option v-for="item in menuType" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item label="一级菜单" prop="parentId" v-if="ruleForm.menuType == 'C'" class="spread">
              <el-select v-model="ruleForm.parentId" filterable placeholder="请选择" @change="handleParentId">
                <el-option v-for="item in tableData" :key="item.fid" :label="item.menuName" :value="item.fid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item :label="$t('system.menu_name')" prop="menuName">
              <el-input v-model="ruleForm.menuName" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item :label="$t('system.routing_address')">
              <el-input v-model="ruleForm.url" placeholder="" :disabled="ruleForm.disabled" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item :label="$t('system.display_order')">
              <el-input-number v-model="ruleForm.orderNum" :min="1"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" :loading="loading"
          @click="handleConfirm('ruleForm')">{{ $t("common.preservation") }}</el-button>
        <el-button @click="handleClose()" size="small">{{ $t("common.cancel") }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { userAdmin } from "@/api/userAdmin"
export default {
  data () {
    let urlFn = (rule, value, callback) => {
      if (this.ruleForm.menuType == 'C') {
        if (!value) {
          return callback(new Error('路由地址不能为空'));
        } else {
          callback();
        }
      } else {
        callback();
      }


    };
    return {
      height: "calc(100vh - 180px)",
      tableData: [],
      tableLoading: false,
      radioId: "",
      childRadioId: '',
      formData: {
        keyWord: "",
      },
      ruleForm: {
        menuName: "",
        orderNum: "1",
        menuType: 'M',
        parentId: '',
        url: ""
      },
      rules: {
        menuName: [{ required: true, message: '菜单名称不能为空', trigger: 'blur' }],
        url: [{ validator: urlFn, message: '路由地址不能为空', trigger: 'blur' }],
        menuType: [{ required: true, message: '请选择菜单类型', trigger: 'change' }],
        parentId: [{ required: true, message: '一级菜单不能为空', trigger: 'change' }],
      },
      title: "添加",
      isShowAdd: false,
      isShowAddSecond: false,
      loading: false,
      menuType: [{
        label: '目录',
        value: "M"
      }, {
        label: '菜单',
        value: "C"
      }]
    }
  },
  created () {
    this.getSysMenuList()
  },
  methods: {
    handleSearch () {
      this.getSysMenuList()
    },
    getSysMenuList () {
      const param = {
        menuName: this.formData.keyWord,
        field: 'orderNum',
        order: 'ASC',
      }
      this.tableLoading = true
      userAdmin.getSysMenuList(param).then(res => {
        this.tableLoading = false
        if (res.code == 200) {
          this.tableData = res.data.rows
        }
      })
    },
    rowClick (row) {
      this.childRadioId = ""
      console.log(row)
      this.radioId = row.fid
      this.$refs.refTable.setCurrentRow(row);
    },
    rowClickChild (row) {
      this.childRadioId = row.fid
      this.radioId = row.parentId
      // this.tableData.find(item => item.fid == row.parentId)
      this.$refs.refTable1.setCurrentRow(row);
    },
    handleAdd () {
      this.title = this.$t('dialog.menu_add')
      this.ruleForm = {
        menuName: "",
        orderNum: "1",
        menuType: '',
        url: "",
      }

      try {
        this.$refs['ruleForm'].resetFields();
      } catch (e) { }
      this.isShowAdd = true

    },
    handleClose () {
      this.isShowAdd = false
    },
    handleConfirm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let param = Object.assign({}, this.ruleForm)
          param.parentId = param.parentId || null
          this.loading = true
          userAdmin.addSysMenu(param, this.title).then(res => {
            this.loading = false
            if (res.code == 200) {
              if (this.ruleForm.menuType == 'M') { //一级菜单
                // this.getSysMenuList()
              } else {
                const index = this.tableData.findIndex(item => item.fid == this.ruleForm.parentId)
                if (index > -1) {
                  if (this.title == '添加菜单') {
                    this.tableData[index].children.push(res.data)
                  } else {
                    const key = this.tableData[index].children.findIndex(item => item.fid == this.childRadioId)
                    if (key > -1) {
                      Object.assign(this.tableData[index].children[key], this.ruleForm)
                      console.log(this.tableData[index].children[key])
                    }

                  }

                }
              }
              this.isShowAdd = false
              this.getSysMenuList()
            } else {
              this.$message.error(res.msg);
            }
          })
        }
      })
    },
    handleEdit () {
      if (this.radioId === '') {
        this.$message.error('请选择要修改的菜单');
        return
      }
      let fid = this.childRadioId ? this.childRadioId : this.radioId
      userAdmin.findSysMenu(fid).then(res => {
        if (res.code == 200) {
          let routes = this.$router.options.routes[0].children
          if (res.data.menuType == 'M') {
            const index = routes.findIndex(item => (item.path == res.data.url) || res.data.url == '/reportFormInfo/:id')
            res.data.disabled = index > -1 ? true : false
          } else if (res.data.menuType == 'C') {
            let temp = []
            routes.forEach(item => {
              if (item.children) {
                temp.push(...item.children)
              }
            })
            const index = temp.findIndex(item => (item.path == res.data.url) || res.data.url == '/reportFormInfo/:id')
            res.data.disabled = index > -1 ? true : false
          }
          this.title = this.$t('dialog.menu_edit')

          this.$nextTick(() => {
            try {
              this.$refs['ruleForm'].resetFields();
            } catch (e) { }

            Object.assign(this.ruleForm, res.data)
            this.isShowAdd = true
          })


        }
      })
    },
    handleDel () {
      if (this.radioId === '') {
        this.$message.error(this.$t('dialog.please_sel_del'));
        return
      }
      let that = this
      let fid = this.childRadioId ? this.childRadioId : this.radioId
      let ele = {}
      const el = this.tableData.find(item => item.fid == this.radioId)  //找到一级菜单
      if (this.childRadioId) { //选中二级菜单
        const el1 = el.children.find(item => item.fid == this.childRadioId) //找到二级菜单
        ele = el1
      } else {
        ele = el
      }
      console.log(el)
      userAdmin.findSysMenu(fid).then(res => {
        if (res.code == 200) {
          this.$customConfirm({
            content: this.$t('dialog.del_meter') + ' ' + ele.menuName,
            onok () {
              userAdmin.removeSysMenu(fid).then(res => {
                if (res.code == 200) {
                  if (that.childRadioId) {
                    that.childRadioId = ''

                    const index = el.children.findIndex(item => item.fid == fid)
                    if (index > -1) {
                      el.children.splice(index, 1)
                    }
                  } else {
                    that.radioId = ""
                    that.childRadioId = ''
                    that.getSysMenuList()
                  }

                  that.$message({ duration: 1000, type: 'success', message: '删除成功!' });
                }
              })
            }
          })
        }
      })
    },
    changeMenuType () {
      // this.ruleForm.parentId = ''
    },
    handleParentId () {
      this.$forceUpdate()
    },
    getRowClass (row) {
      let data = row.row;
      let res = [];
      if (data.children && data.children.length > 0) {
        res.push('row-expand-has');
        return res;
      } else {
        res.push('row-expand-unhas');
        return res;
      }
    },
    getMenuType (row) {
      if (row.menuType == 'M' && !row.url) {
        return '目录'
      } else if (row.menuType == 'M' && row.url) {
        return '菜单'
      } else {
        return ''
      }
    }
  }
}
</script>
<style scoped>
.btngroup {
  float: right;
  padding-right: 15px;
  margin-top: -10px;
}
.tableAuto >>> .el-table__expanded-cell {
  padding: 5px;
}
.spread >>> .el-select {
  width: 100%;
}
.tableAuto >>> .row-expand-unhas .el-table__expand-column {
  pointer-events: none;
}
.tableAuto >>> .row-expand-unhas .el-table__expand-column .el-icon {
  visibility: hidden;
}
</style>